package com.dbw.englishassistant.service;

public class MarkdownLineTool {

    public enum MarkdownType {
        GENERAL_TEXT,
        QUOTATION,
        TITLE,
    }
    
    public static class MarkdownItem {
        
        private String markdownLine = "";
        
        private MarkdownType lineType = MarkdownType.GENERAL_TEXT;
        
        private String pureText = "";

        public String getMarkdownLine() {
            return markdownLine;
        }

        public void setMarkdownLine(String markdownLine) {
            this.markdownLine = markdownLine;
        }

        public MarkdownType getLineType() {
            return lineType;
        }

        public void setLineType(MarkdownType lineType) {
            this.lineType = lineType;
        }

        public String getPureText() {
            return pureText;
        }

        public void setPureText(String pureText) {
            this.pureText = pureText;
        }
        
    }
    
    private MarkdownItem markdownItem = null;
    
    public MarkdownLineTool() {
        
    }
    
    public MarkdownItem parseLine(String line) {
        
        markdownItem = new MarkdownItem();
        
        if(line == null) {
            return markdownItem;
        }
        
        line = line.trim();
        markdownItem.setMarkdownLine(line);
        parseType();
        extracePureText();
        
        return markdownItem; 
    }
    
    private void parseType() {
        String markdownLine = markdownItem.getMarkdownLine();
        
        if(markdownLine.isEmpty()) {
            markdownItem.setLineType(MarkdownType.GENERAL_TEXT);
            return;
        }
        
        switch(markdownLine.charAt(0)) {
        case '#':
            markdownItem.setLineType(MarkdownType.TITLE);
            break;
        case '>':
            markdownItem.setLineType(MarkdownType.QUOTATION);
            break;
        default:
            markdownItem.setLineType(MarkdownType.GENERAL_TEXT);
            break;
        }
    }
    
    private void extracePureText() {
        String tmpPureText = markdownItem.getMarkdownLine();
        tmpPureText = tmpPureText.replaceAll("(?<!\\\\)\\*{2}(.*?)(?<!\\\\)\\*{2}", "$1");
        tmpPureText = tmpPureText.replaceAll("(?<!\\\\)\\*(.*?)(?<!\\\\)\\*", "$1");
        tmpPureText = tmpPureText.replaceAll("(?<!\\\\)\\+{2}(.*?)(?<!\\\\)\\+{2}", "$1");
        tmpPureText = tmpPureText.replaceAll("(?<!\\\\)\\={2}(.*?)(?<!\\\\)\\={2}", "$1");
        tmpPureText = tmpPureText.replaceAll("\\\\(.)", "$1");
        tmpPureText = tmpPureText.replaceAll("^>", "");
        tmpPureText = tmpPureText.trim();
        
        markdownItem.setPureText(tmpPureText);
    }
    
    public MarkdownItem getMarkdownItem() {
        return markdownItem;
    }

}
